import { Tree } from 'antd';
import React, { FC, useContext, useEffect, useState } from 'react';
import { DesignRedux } from '../DesignRedux';

const LevelTree: FC = (props: any) => {
  const { globalState, dispatch } = useContext(DesignRedux);
  const { schema } = globalState;

  const onDrop = (info: any) => {
    const dropKey = info.node.key;
    const dragKey = info.dragNode.key;

    // todo 添加一些禁止拖拽
    // 通过 key 选找对象
    const loop = (data: any, key: string, callback: any) => {
      for (let i = 0; i < data.length; i++) {
        if (data[i].key === key) {
          return callback(data[i], i, data);
        }
        if (data[i].children) {
          loop(data[i].children, key, callback);
        }
      }
    };
    const data = [...schema];

    // 找到拖拽的对象
    let dragObj = null;

    loop(data, dragKey, (item: any, index: number, arr: Array<any>) => {
      arr.splice(index, 1);
      dragObj = item;
    });

    if (!info.dropToGap) {
      // 目标对象为子集
      loop(data, dropKey, (item: object) => {
        item.children = item.children || [];
        item.children.unshift(dragObj);
      });
    } else {
      loop(data, dropKey, (item: any, index: number, arr: Array<any>) => {
        // 与目标对象为同一等级
        arr.splice(index + 1, 0, dragObj);
      });
    }

    // 更新
    // setSchema(data);
    dispatch({ schema: data });
  };

  const onSelectNode = (selectedKeys, event) => {
    const { node: rightNode, selected } = event;
    dispatch({ rightNode }); // 更新全局变量
  };

  return (
    <Tree
      onSelect={onSelectNode}
      showLine={true}
      draggable
      blockNode
      defaultExpandParent={true}
      defaultExpandAll={true}
      // onDragEnter={this.onDragEnter}
      onDrop={onDrop}
      treeData={schema}
    />
  );
};

export default LevelTree;
